﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

namespace XMK.Framework.DataAccess
{
    /// <summary>
    /// MS-Sql Server数据库驱动
    /// </summary>
    public partial class SqlDbProvider : DbProvider
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connString">数据库连接字符串</param>
        public SqlDbProvider(string connString)
        {
            this.ConnString = connString;
        }
        /// <summary>
        /// 实例化数据库操作命令
        /// </summary>
        /// <returns>数据库操作命令</returns>
        public override IDbCommand CreateCommand()
        {
            return new SqlCommand();
        }
        /// <summary>
        /// 实例化数据库连接
        /// </summary>
        /// <returns>数据库连接</returns>
        public override IDbConnection CreateConnection()
        {
            return new SqlConnection();
        }
        /// <summary>
        /// 实例化数据库适配器
        /// </summary>
        /// <returns>数据库适配器</returns>
        public override IDbDataAdapter CreateDataAdapter()
        {
            return new SqlDataAdapter();
        }
        /// <summary>
        /// 实例化数据库参数
        /// </summary>
        /// <returns>数据库操作的参数</returns>
        public override IDbDataParameter CreateParameter()
        {
            return new SqlParameter();
        }
        /// <summary>
        /// 取得参数的前缀
        /// </summary>
        public override string ParamPrefix
        {
            get { return "@"; }
        }

        /// <summary>
        /// 开始数据库缓存依赖
        /// </summary>
        public override void DbDependencyStart()
        {
            SqlDependency.Start(this.ConnString);
        }
        /// <summary>
        /// 结束数据库缓存依赖
        /// </summary>
        public override void DbDependencyStop()
        {
            SqlDependency.Stop(this.ConnString);
        }
        /// <summary>
        /// 创建数据库依赖
        /// </summary>
        /// <typeparam name="T">数据库依赖保存的列表类型</typeparam>
        /// <param name="sqlText">数据库依赖查询字符串</param>
        /// <param name="fun">反序列化类型委托</param>
        /// <returns>数据库依赖实现类</returns>
        public override DbDependency<T> CreateDbDependency<T>(string sqlText,DataRowFullInfoFun<T> fun)
        {
            return new SqlDbDependency<T>(this.ConnString, sqlText,fun);
        }
        /// <summary>
        /// 对命令进行参数填充处理
        /// </summary>
        /// <param name="cmd">命令实例</param>
        /// <param name="dbCmdInfo">命令信息</param>
        internal override void DeriveParameters(IDbCommand cmd, DbCmdInfo dbCmdInfo)
        {            
            for (int i = 0; i < dbCmdInfo.Params.Count; i++)
            {
                cmd.Parameters.Add(dbCmdInfo.Params[i]);
            }
        }

    }
}
